/// 用户历史记录响应模型
/// 对应接口: POST /users/daily_activities_comments/
class UserHistoryResponse {
  /// 响应状态
  final String status;
  
  /// 历史记录数据列表
  final List<HistoryItemData> data;
  
  /// 总数
  final int total;
  
  /// 查询日期
  final String date;
  
  /// 用户ID
  final String userId;
  
  /// 响应消息
  final String? message;

  UserHistoryResponse({
    required this.status,
    required this.data,
    required this.total,
    required this.date,
    required this.userId,
    this.message,
  });

  /// 是否成功
  bool get isSuccess => status == 'success';

  /// 从JSON创建实例
  factory UserHistoryResponse.fromJson(Map<String, dynamic> json) {
    final dataList = json['data'] as List? ?? [];
    
    return UserHistoryResponse(
      status: json['status'] ?? 'error',
      data: dataList.map((item) => HistoryItemData.fromJson(item)).toList(),
      total: json['total'] ?? 0,
      date: json['date'] ?? '',
      userId: json['userId'] ?? '',
      message: json['message'],
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'status': status,
      'data': data.map((item) => item.toJson()).toList(),
      'total': total,
      'date': date,
      'userId': userId,
      if (message != null) 'message': message,
    };
  }

  @override
  String toString() {
    return 'UserHistoryResponse(status: $status, total: $total, data: ${data.length} items, date: $date)';
  }
}

/// 历史记录数据项模型
class HistoryItemData {
  /// 项目ID
  final int? id;
  
  /// 项目类型（"activity" 或 "comment"）
  final String? type;
  
  /// 标题
  final String? title;
  
  /// 内容/描述
  final String? content;
  
  /// 地点
  final String? location;
  
  /// 发布时间
  final String? publishTime;
  
  /// 状态
  final String? status;
  
  /// 参与人数（仅活动类型）
  final int? participantCount;
  
  /// 最大参与人数（仅活动类型）
  final int? maxParticipants;
  
  /// 点赞数（仅评论类型）
  final int? likeCount;
  
  /// 评论数（仅评论类型）
  final int? commentCount;
  
  /// 🔥 新增：图片列表
  final List<String>? images;
  
  /// 🔥 新增：分类标签
  final List<String>? category;
  
  /// 🔥 新增：发布者ID
  final int? publisherId;
  
  /// 🔥 新增：发布者头像
  final String? publisherAvatar;
  
  /// 🔥 新增：发布者昵称
  final String? publisherNickname;
  
  /// 扩展数据
  final Map<String, dynamic>? extraData;

  HistoryItemData({
    this.id,
    this.type,
    this.title,
    this.content,
    this.location,
    this.publishTime,
    this.status,
    this.participantCount,
    this.maxParticipants,
    this.likeCount,
    this.commentCount,
    this.images,
    this.category,
    this.publisherId,
    this.publisherAvatar,
    this.publisherNickname,
    this.extraData,
  });

  /// 是否为活动类型
  bool get isActivity => type == 'activity';
  
  /// 是否为评论类型
  bool get isComment => type == 'comment';

  /// 从JSON创建实例
  factory HistoryItemData.fromJson(Map<String, dynamic> json) {
    // 🔥 修复：正确映射服务器返回的字段
    return HistoryItemData(
      id: json['id'] ?? json['activityId'] ?? json['commentId'],
      type: _normalizeType(json['type'] ?? _determineType(json)),
      title: json['title'] ?? json['activityTitle'] ?? json['commentTitle'],
      content: json['content'] ?? json['activityDetails'] ?? json['commentContent'],
      location: json['location'] ?? json['activityLocation'] ?? json['commentLocation'],
      publishTime: json['createTime'] ?? json['publishTime'] ?? json['activityPublishTime'] ?? json['commentPublishTime'],
      status: json['status'] ?? json['activityStatus'] ?? 'normal',
      participantCount: json['currentParticipants'] ?? json['participantCount'] ?? json['activityCurrentParticipants'],
      maxParticipants: json['maxParticipants'] ?? json['activityMaxParticipants'],
      likeCount: json['likeCount'] ?? json['commentLikeCount'],
      commentCount: json['commentCount'],
      images: _parseImageList(json['images']),
      category: _parseStringList(json['category']),
      publisherId: json['publisherId'],
      publisherAvatar: json['publisherAvatar'],
      publisherNickname: json['publisherNickname'],
      extraData: json['extraData'] is Map ? Map<String, dynamic>.from(json['extraData']) : null,
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      if (id != null) 'id': id,
      if (type != null) 'type': type,
      if (title != null) 'title': title,
      if (content != null) 'content': content,
      if (location != null) 'location': location,
      if (publishTime != null) 'publishTime': publishTime,
      if (status != null) 'status': status,
      if (participantCount != null) 'participantCount': participantCount,
      if (maxParticipants != null) 'maxParticipants': maxParticipants,
      if (likeCount != null) 'likeCount': likeCount,
      if (commentCount != null) 'commentCount': commentCount,
      if (images != null) 'images': images,
      if (category != null) 'category': category,
      if (publisherId != null) 'publisherId': publisherId,
      if (publisherAvatar != null) 'publisherAvatar': publisherAvatar,
      if (publisherNickname != null) 'publisherNickname': publisherNickname,
      if (extraData != null) 'extraData': extraData,
    };
  }

  /// 根据JSON内容判断类型
  static String _determineType(Map<String, dynamic> json) {
    if (json.containsKey('activityId') || json.containsKey('activityTitle')) {
      return 'activity';
    } else if (json.containsKey('commentId') || json.containsKey('commentTitle')) {
      return 'comment';
    }
    return 'unknown';
  }

  /// 🔥 新增：标准化类型字段（中文转英文）
  static String _normalizeType(String? type) {
    if (type == null) return 'unknown';
    switch (type) {
      case '活动':
        return 'activity';
      case '评论':
        return 'comment';
      default:
        return type;
    }
  }

  /// 🔥 新增：解析图片列表
  static List<String>? _parseImageList(dynamic images) {
    if (images == null) return null;
    if (images is List) {
      return images.map((e) => e.toString()).toList();
    }
    return null;
  }

  /// 🔥 新增：解析字符串列表
  static List<String>? _parseStringList(dynamic list) {
    if (list == null) return null;
    if (list is List) {
      return list.map((e) => e.toString()).toList();
    }
    return null;
  }

  @override
  String toString() {
    return 'HistoryItemData(id: $id, type: $type, title: $title, publishTime: $publishTime)';
  }
}
